import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import api from '../../services/api';
import './LoginPage.css';

function LoginPage({ onLogin }) {
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        username: '',
        password: '',
        email: '',
        verificationCode: ''
    });
    const [showPassword, setShowPassword] = useState(false);
    const [loading, setLoading] = useState(false);
    const [verifyLoading, setVerifyLoading] = useState(false);
    const [message, setMessage] = useState({ type: '', text: '' });
    const [banInfo, setBanInfo] = useState(null); // 新增：封禁信息状态

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleGetVerifyCode = async () => {
        if (!formData.username || !formData.email) {
            setMessage({ type: 'error', text: '请先填写用户名和邮箱' });
            return;
        }

        setVerifyLoading(true);
        try {
            const result = await api.getVerifyCode(formData.username, formData.email, 1);
            if (result.code === 200) {
                setMessage({ type: 'success', text: '验证码已发送到您的邮箱' });
            } else {
                //setMessage({ type: 'error', text: result.message || '发送验证码失败' });
            }
        } catch (error) {
            //setMessage({ type: 'error', text: '发送验证码失败' });
        } finally {
            setVerifyLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!formData.username || !formData.password || !formData.email || !formData.verificationCode) {
            setMessage({ type: 'error', text: '请填写所有必填字段' });
            return;
        }

        setLoading(true);
        setBanInfo(null); // 清除之前的封禁信息

        try {
            const result = await api.login(formData);

            console.log('=== 登录结果检查 ===');
            console.log('登录返回结果:', result);
            console.log('用户数据:', result.data);
            console.log('封禁状态:', result.data?.isBanned);

            // 检查用户是否被封禁
            const userData = result.data || result;
            const isBanned = userData.isBanned || userData.banned; // 兼容不同的字段名

            if (isBanned === true) {
                console.log('⚠️ 用户已被封禁，拒绝登录');

                // 设置封禁信息
                setBanInfo({
                    username: userData.username || formData.username,
                    banReason: userData.banReason || '违反社区规定',
                    banTime: userData.banTime || userData.bannedAt || new Date().toISOString(),
                    contactInfo: '如有疑问，请联系管理员'
                });

                setMessage({
                    type: 'ban',
                    text: '您的账号已被封禁，无法登录'
                });
                return; // 阻止登录流程继续
            }

            // 用户未被封禁，正常登录
            console.log('✅ 用户状态正常，允许登录');
            setMessage({ type: 'success', text: '登录成功' });
            onLogin(result, result.token);
            navigate('/social');

        } catch (error) {
            console.error('登录失败:', error);
            setMessage({ type: 'error', text: error.message || '登录失败' });
        } finally {
            setLoading(false);
        }
    };

    // 格式化封禁时间
    const formatBanTime = (timeString) => {
        try {
            const date = new Date(timeString);
            return date.toLocaleString('zh-CN');
        } catch (error) {
            return '未知时间';
        }
    };

    return (
        <div className="login-container">
            <div className="login-form-container card">
                <div className="login-title card-header">
                    <h1 className="card-title">用户登录</h1>
                    <p className="card-subtitle">欢迎回到PT站</p>
                </div>

                {message.text && (
                    <div className={`message ${message.type}`}>
                        {message.text}
                    </div>
                )}

                {/* 封禁信息显示 */}
                {banInfo && (
                    <div className="ban-info-container">
                        <div className="ban-info-header">
                            <span className="ban-icon">🚫</span>
                            <h3>账号已被封禁</h3>
                        </div>
                        <div className="ban-info-details">
                            <div className="ban-detail-item">
                                <span className="ban-label">用户名：</span>
                                <span className="ban-value">{banInfo.username}</span>
                            </div>
                            <div className="ban-detail-item">
                                <span className="ban-label">封禁原因：</span>
                                <span className="ban-value">{banInfo.banReason}</span>
                            </div>
                            <div className="ban-detail-item">
                                <span className="ban-label">封禁时间：</span>
                                <span className="ban-value">{formatBanTime(banInfo.banTime)}</span>
                            </div>
                            <div className="ban-contact">
                                <span className="ban-contact-icon">📧</span>
                                {banInfo.contactInfo}
                            </div>
                        </div>
                    </div>
                )}

                <form onSubmit={handleSubmit} className="login-form">
                    <div className="form-group">
                        <label className="form-label">
                            👤 用户名
                        </label>
                        <input
                            type="text"
                            name="username"
                            value={formData.username}
                            onChange={handleInputChange}
                            className="form-input"
                            placeholder="请输入用户名"
                            required
                            disabled={banInfo} // 如果被封禁，禁用输入框
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">
                            📧 邮箱
                        </label>
                        <input
                            type="email"
                            name="email"
                            value={formData.email}
                            onChange={handleInputChange}
                            className="form-input"
                            placeholder="请输入邮箱地址"
                            required
                            disabled={banInfo} // 如果被封禁，禁用输入框
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">
                            🔒 密码
                        </label>
                        <div className="password-container">
                            <input
                                type={showPassword ? 'text' : 'password'}
                                name="password"
                                value={formData.password}
                                onChange={handleInputChange}
                                className="form-input"
                                placeholder="请输入密码"
                                required
                                disabled={banInfo} // 如果被封禁，禁用输入框
                            />
                            <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="password-toggle"
                                disabled={banInfo} // 如果被封禁，禁用按钮
                            >
                                {showPassword ? '🙈' : '👁️'}
                            </button>
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">
                            🔑 验证码
                        </label>
                        <div className="verify-group">
                            <input
                                type="text"
                                name="verificationCode"
                                value={formData.verificationCode}
                                onChange={handleInputChange}
                                className="form-input verify-input"
                                placeholder="请输入验证码"
                                required
                                disabled={banInfo} // 如果被封禁，禁用输入框
                            />
                            <button
                                type="button"
                                onClick={handleGetVerifyCode}
                                disabled={verifyLoading || banInfo} // 如果被封禁，禁用按钮
                                className="verify-btn"
                            >
                                {verifyLoading ? '发送中...' : '获取验证码'}
                            </button>
                        </div>
                    </div>

                    <button
                        type="submit"
                        disabled={loading || banInfo} // 如果被封禁，禁用登录按钮
                        className={`btn btn-full ${banInfo ? 'btn-disabled' : ''}`}
                    >
                        {banInfo ? '账号已封禁' : (loading ? '登录中...' : '登录')}
                    </button>
                </form>

                <div className="login-footer">
                    <p>
                        还没有账号？
                        <Link to="/register" className="form-link">
                            立即注册
                        </Link>
                    </p>

                    {banInfo && (
                        <div className="ban-footer-tip">
                            <p>如需申诉封禁，请联系管理员</p>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

export default LoginPage;